package com.atos.optical.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.atos.optical.common.BaseServiceImpl;
import com.atos.optical.common.ServiceException;
import com.atos.optical.mapper.SysUserMenuRelMapper;
import com.atos.optical.model.bo.SysUserMenuRelBo;
import com.atos.optical.model.po.SysUserMenuRel;
import com.atos.optical.service.SysUserMenuRelService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author wanghra
 * @version 1.0
 * @description
 * @date 2025/8/13
 */
@Slf4j
@Service
public class SysUserMenuRelServiceImpl extends BaseServiceImpl<SysUserMenuRelMapper,
        SysUserMenuRel> implements SysUserMenuRelService {
    @Autowired
    private SysUserMenuRelMapper mapper;

    @Override
    @Transactional
    public boolean addUserMenuRel(SysUserMenuRelBo bo) {
        check(bo);
        List<SysUserMenuRel> userMenuRelList = bo.getMenuIdList().stream().filter(StrUtil::isNotBlank).map(menuId -> new SysUserMenuRel().setUserId(bo.getUserId()).setMenuId(menuId))
                .collect(Collectors.toList());
        QueryWrapper<SysUserMenuRel> query = new QueryWrapper<>();
        query.lambda().eq(SysUserMenuRel::getUserId, bo.getUserId())
                .eq(SysUserMenuRel::getMenuId, bo.getMenuIdList());
        super.remove(query);
        return super.saveBatch(userMenuRelList);
    }

    @Override
    public boolean deleteUserMenuRel(SysUserMenuRelBo bo) {
        check(bo);
        QueryWrapper<SysUserMenuRel> query = new QueryWrapper<>();
        query.lambda().eq(SysUserMenuRel::getUserId, bo.getUserId())
                .eq(SysUserMenuRel::getMenuId, bo.getMenuIdList());
        return super.remove(query);
    }

    private void check(SysUserMenuRelBo bo) {
        if (StrUtil.isBlank(bo.getUserId())) {
            throw new ServiceException("用户信息为空，请联系管理员！");
        }
        if (CollUtil.isEmpty(bo.getMenuIdList())) {
            throw new ServiceException("菜单信息为空，请联系管理员！");
        }
    }
}
